import { makeObservable, observable, action, reaction } from 'mobx'
import { getUserInfoApi } from '@/request/api/master'

class UserInfoStore {
  nickname: string = 'nickname'
  avatar: string = ''
  loginStatus: boolean = false

  constructor() {
    makeObservable(this, {
      nickname: observable,
      avatar: observable,
      loginStatus: observable,
      setLoginStatus: action,
      getUserInfo: action,
    })
  }

  getNickname() {
    return this.nickname
  }

  getAvatar() {
    return this.avatar
  }

  setLoginStatus(status: boolean) {
    this.loginStatus = status
  }

  async getUserInfo() {
    const res = await getUserInfoApi()
    if (res.code !== 200) {
      this.loginStatus = false
      return window.localStorage.removeItem('token')
    }

    this.nickname = res.data.nickname
    this.avatar = res.data.avatar
    this.loginStatus = true
  }

  onNicknameChange(callback) {
    return reaction(
      () => this.nickname,
      (newNickname) => callback(newNickname)
    )
  }

  onAvatarChange(callback) {
    return reaction(
      () => this.avatar,
      (newAvatar) => callback(newAvatar)
    )
  }

  onLoginStatusChange(callback) {
    return reaction(
      () => this.loginStatus,
      (newStatus) => callback(newStatus)
    )
  }
}

export const userInfoStore = new UserInfoStore()
